package com.tang.dict;

import com.tang.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public abstract class ExecutableDictParser extends MergeDictParse {
    AtomicInteger integer = new AtomicInteger(0);
    ExecutorService executor = null;

    public ExecutableDictParser() {
        executor = createThreadPoolExecutor();
    }

    private ExecutorService createThreadPoolExecutor() {
        return Executors.newFixedThreadPool(5, r -> {
            Thread thread = new Thread(r);
            thread.setName("dict parser thread" + integer.getAndAdd(1));
            return thread;
        });
    }

    protected void execute(List<DictParseField> dictParseFields) {
        List<DictParseField> fields = mergeFields(dictParseFields);
        List<Future> list = CommonUtils.newList();
        for (DictParseField field : fields) {
            List<DictParseField> parserFields = getParserFields();
            Future submit = executor.submit(() -> {
                setParserFields(parserFields);
                this.execute(field);
            });
            list.add(submit);
        }
        waitQuery(list);
    }

    private void waitQuery(List<Future> list) {
        for (Future future : list) {
            try {
                future.get();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    public abstract List<DictParseField> getParserFields();
    public abstract void setParserFields(List<DictParseField> fields);
}
